﻿var tempDetailSetting = null;
var AllImgExt = ".jpg|.jpeg|.bmp|.png|";
var ImgObj = new Image();
var maxWidth = 380;
var maxHeight = 252;
var basicSetting = null;

//个人设置-详细资料 右侧内容缓存
var detailSetting = null;
var xmlHtttpRequest = null;
$().ready(function () {

    //个人设置-会员信息按钮
    $("#setting-vipInfoButton").click(function () {
        document.getElementById("setting-vipInfoButton").className = "expertInterview-side-item-selected";
        document.getElementById("setting-detailButton").className = "expertInterview-side-item";
        document.getElementById("setting-basicButton").className = "expertInterview-side-item";
        document.getElementById("setting-basicButton").className = "expertInterview-side-item";
        document.getElementById("setting-CouponInfoButton").className = "expertInterview-side-item";

        $.get("/account/settingvipinfo", function (data) {
            $("#setting-contentRight").html(data);
        })
    });

    //将右侧基本资料内容进行缓存
    basicSetting = $("#setting-contentRight").html();

    //个人设置-基本资料按钮
    $("#setting-basicButton").click(function () {
        if (basicSetting == null)
            return;
        document.getElementById("setting-detailButton").className = "expertInterview-side-item";
        document.getElementById("setting-basicButton").className = "expertInterview-side-item-selected";
        document.getElementById("setting-vipInfoButton").className = "expertInterview-side-item";
        document.getElementById("setting-CouponInfoButton").className = "expertInterview-side-item";

        $("#setting-contentRight").html("");
        $("#setting-contentRight").html(basicSetting);




        //基本资料保存按钮
        $("#srtting-saveBtn").click(function () {
            if (document.getElementById("srtting-saveBtn").className == "booui_disabledbutton booui_button_small")
                return;

            var nickname = $("#nickname").val();
            if (nickname.length < 2 || nickname.length > 8) {
                $("#messageSpan").html("昵称必须2-8位");
                $("#settingNicknameMessage").css("visibility", "visible");
                return;
            }


            if (!checkNamename(nickname)) {
                $("#messageSpan").html("不能包含特殊字符！");
                $("#settingNicknameMessage").css("visibility", "visible");
                return;
            }

            document.getElementById("srtting-saveBtn").className = "booui_disabledbutton booui_button_small";

            //点击保存按钮仅保存个人昵称
            $.post("/Account/ChangeNickname", { nickname: nickname }, function (data) {
                document.getElementById("srtting-saveBtn").className = "booui_bluebutton booui_button_small";
                var res = JSON.parse(data);
                if (res.Status == "success" && res.Message == "ok") {
                    $("#setting-saveMessage").css("visibility", "visible");
                }
                else {
                    $("#setting-saveMessage").html(res.Message);
                    $("#setting-saveMessage").css("visibility", "visible");
                }
            });
        });



    });

    //个人设置-详细资料按钮
    $("#setting-detailButton").click(function () {

        if (detailSetting != null)
        {
            document.getElementById("setting-detailButton").className = "expertInterview-side-item-selected";
            document.getElementById("setting-basicButton").className = "expertInterview-side-item";
            document.getElementById("setting-vipInfoButton").className = "expertInterview-side-item";
            document.getElementById("setting-CouponInfoButton").className = "expertInterview-side-item";

            $("#setting-contentRight").html("");
            $("#setting-contentRight").html(detailSetting);

            //个人设置-详细资料-保存按钮
            $("#setting-detailSaveButton").click(function () {

                var detailName = $("#detailName").val();
                if (detailName == "") {
                    $("#settingNameMessage").css("visibility", "visible");
                    return;
                }
                $("#detailName").attr("value", $("#detailName").val());

                var email = $("#email").val();
                if (!checkEmail(email)) {
                    $("#settingEmailMessage").css("visibility", "visible");
                    return;
                }
                $("#email").attr("value", $("#email").val());

                var detailCompanyOrSchool = $("#detailCompanyOrSchool").val();
                if (detailCompanyOrSchool == "") {
                    $("#settingSchoolMessage").css("visibility", "visible");
                    return;
                }
                $("#detailCompanyOrSchool").attr("value", $("#detailCompanyOrSchool").val());

                var detailJobTitle = $("#detailJobTitle").val();
                if (detailJobTitle == "") {
                    $("#settingJobMessage").css("visibility", "visible");
                    return;
                }
                $("#detailJobTitle").attr("value", $("#detailJobTitle").val());

                var phone = $("#phone").val();
                if (!isMobil(phone)) {
                    $("#settingPhoneMessage").css("visibility", "visible");
                    return;
                }
                $("#phone").attr("value", $("#phone").val());


                //if (document.getElementById("seriesCourseSendMessage").checked) {
                //    $("#seriesCourseSendMessage").attr("checked", "checked");
                //    $("#seriesCourseSendMessage").attr("value", "on");
                //}
                //else {
                //    $("#seriesCourseSendMessage").removeAttr("checked");
                //    $("#seriesCourseSendMessage").removeAttr("value");
                //}

                if ($("input[name='Sex']:checked").val() == "true") {
                    $("#detailGirlSex").removeAttr("checked");
                    $("#detailBoySex").attr("checked", "checked");
                }
                else {
                    $("#detailBoySex").removeAttr("checked");
                    $("#detailGirlSex").attr("checked", "checked");
                }
               

                tempDetailSetting = $("#setting-contentRight").html();
                $("#setting-detailForm").ajaxSubmit({
                    url: "/account/ChangeDetail",
                    success: changeDetailSuccess,
                });
            });

            $(".settingFormItemTextInput").focus(function () {
                hideSettingMessagelabel();
            });

            return;
        }

        //异步请求账户详细资料
        $.post("/Account/SettingDetail", function (data) {
            document.getElementById("setting-detailButton").className = "expertInterview-side-item-selected";
            document.getElementById("setting-basicButton").className = "expertInterview-side-item";
            document.getElementById("setting-vipInfoButton").className = "expertInterview-side-item";
            document.getElementById("setting-CouponInfoButton").className = "expertInterview-side-item";



            //将服务器响应内容存储到作为变量的缓存中
            detailSetting = data;

            $("#setting-contentRight").html(data);

            //个人设置-详细资料-保存按钮
            $("#setting-detailSaveButton").click(function () {

                var detailName = $("#detailName").val();
                if (detailName == "") {
                    $("#settingNameMessage").css("visibility", "visible");
                    return;
                }
                $("#detailName").attr("value", $("#detailName").val());

                var email = $("#email").val();
                if (!checkEmail(email)) {
                    $("#settingEmailMessage").css("visibility", "visible");
                    return;
                }
                $("#settingEmailMessage").attr("value", $("#settingEmailMessage").val());

                var detailCompanyOrSchool = $("#detailCompanyOrSchool").val();
                if (detailCompanyOrSchool == "") {
                    $("#settingSchoolMessage").css("visibility", "visible");
                    return;
                }
                $("#detailCompanyOrSchool").attr("value", $("#detailCompanyOrSchool").val());

                var detailJobTitle = $("#detailJobTitle").val();
                if (detailJobTitle == "") {
                    $("#settingJobMessage").css("visibility", "visible");
                    return;
                }
                $("#detailJobTitle").attr("value", $("#detailJobTitle").val());

                var phone = $("#phone").val();
                if (!isMobil(phone)) {
                    $("#settingPhoneMessage").css("visibility", "visible");
                    return;
                }
                $("#phone").attr("value", $("#phone").val());


                //if (document.getElementById("seriesCourseSendMessage").checked) {
                //    $("#seriesCourseSendMessage").attr("checked", "checked");
                //    $("#seriesCourseSendMessage").attr("value", "on");
                //}
                //else {
                //    $("#seriesCourseSendMessage").removeAttr("checked");
                //    $("#seriesCourseSendMessage").removeAttr("value");
                //}


                if ($("input[name='Sex']:checked").val() == "true") {
                    $("#detailGirlSex").removeAttr("checked");
                    $("#detailBoySex").attr("checked", "checked");
                }
                else {
                    $("#detailBoySex").removeAttr("checked");
                    $("#detailGirlSex").attr("checked", "checked");
                }


                tempDetailSetting = $("#setting-contentRight").html();
                $("#setting-detailForm").ajaxSubmit({
                    url: "/account/ChangeDetail",
                    success: changeDetailSuccess,
                });
            });

            $(".settingFormItemTextInput").focus(function () {
                hideSettingMessagelabel();
            });

         });
    });

    //个人设置-优惠券按钮
    $("#setting-CouponInfoButton").click(function () {
        document.getElementById("setting-vipInfoButton").className = "expertInterview-side-item";
        document.getElementById("setting-detailButton").className = "expertInterview-side-item";
        document.getElementById("setting-basicButton").className = "expertInterview-side-item";
        document.getElementById("setting-CouponInfoButton").className = "expertInterview-side-item-selected";

        $.get("/geekbandcoupon/index", function (data) {

            //将服务器端响应放在个人设置右侧区域
            $("#setting-contentRight").html(data);

            window._bd_share_main.init();
        });
    });


    $("#changePasswordCancelButton").click(function () {

        
        $("#setting-passwordEditor").modal('hide');
        
        
    });


    //修改密码时点击的确定按钮
    $("#changePasswordSaveButton").click(function () {

        if (document.getElementById("changePasswordSaveButton").className == "booui_disabledbutton booui_button_small")
            return;

        var oldPassword = $("#oldpassword").val();
        var password = $("#password").val();
        var passwordConfirm = $("#passwordConfirm").val();
        if (oldPassword == "") {
            alert("旧密码不能为空");
            return;
        }
        if (password == "") {
            alert("新密码不能为空");
            return;
        }
        if (passwordConfirm == "") {
            alert("确认密码不能为空");
            return;
        }
        if (password != passwordConfirm) {
            alert("密码不一致");
            return;
        }

        document.getElementById("changePasswordSaveButton").className = "booui_disabledbutton booui_button_small";


        $.post("/Account/ChangePassword", { oldPassword: oldPassword, password: password }, function (data) {
            document.getElementById("changePasswordSaveButton").className = "booui_bluebutton";


            var res = JSON.parse(data);
            if (res.Status == "success" && res.Message == "ok") {
                //密码修改成功后重新加载当前页面
                window.location.reload();
            }
            else {
                alert("旧密码不正确");
            }
        });

    });



    $("#srtting-saveBtn").click(function () {
        if (document.getElementById("srtting-saveBtn").className == "booui_disabledbutton booui_button_small")
            return;

        var nickname = $("#nickname").val();
        if (nickname.length < 2 || nickname.length > 8) {
            $("#messageSpan").html("昵称必须2-8位");
            $("#settingNicknameMessage").css("visibility", "visible");
            return;
        }

        
        if (!checkNamename(nickname)) {
            $("#messageSpan").html("不能包含特殊字符！");
            $("#settingNicknameMessage").css("visibility", "visible");
            return;
        }

        document.getElementById("srtting-saveBtn").className = "booui_disabledbutton booui_button_small";

        $.post("/Account/ChangeNickname", { nickname: nickname }, function (data) {
            document.getElementById("srtting-saveBtn").className = "booui_bluebutton booui_button_small";
            var res = JSON.parse(data);
            if (res.Status == "success" && res.Message == "ok") {
                $("#setting-saveMessage").html("保存成功");
                $("#setting-saveMessage").css("visibility", "visible");
            }
            else {
                $("#setting-saveMessage").html(res.Message);
                $("#setting-saveMessage").css("visibility", "visible");
            }
        });
    });

    $("#nickname").focus(function () {
        $("#settingNicknameMessage").css("visibility", "hidden");
    });

    $("#changeHeadimageCancelButton").click(function () {

        $("#setting-headimageEditor").modal('hide');
        xmlHtttpRequest.abort();
        xmlHtttpRequest = null;
    });


    $("#changeHeadimageSaveButton").click(function () {
        var sender = $(this);
        if ($("#doc").val() == "")
            return;

        if (document.getElementById("changeHeadimageSaveButton").className == "booui_disabledbutton booui_button_small")
            return;

        document.getElementById("changeHeadimageSaveButton").className = "booui_disabledbutton booui_button_small";

        // ClipHeadImage(HttpPostedFileBase headImage, string xPer, string yPer, string widthPer, string heightPer, string angle)
        var formData = new FormData();
        formData.append("headImage", document.getElementById("doc").files[0]);
        formData.append("xPer", $("#x").val());
        formData.append("yPer", $("#y").val());
        formData.append("widthPer", $("#w").val());
        formData.append("heightPer", $("#h").val());
        formData.append("angle", "0");


        xmlHtttpRequest = new XMLHttpRequest();
        xmlHtttpRequest.open('post', "/account/clipheadimage", true);
        xmlHtttpRequest.onreadystatechange = puloadState_Change;
        xmlHtttpRequest.addEventListener("error", uploadFailed, false);

        
        xmlHtttpRequest.upload.addEventListener("progress", uploadProgress, false);
        xmlHtttpRequest.send(formData);
        $("#uploadImageProgress").css("visibility", "visible");


        //$("#crop_form").ajaxSubmit({
        //    url: "/account/ClipHeadImage",
        //    success: uploadImgSuccess,
        //});
    });





    $("#doc").bind("change", function () {
        var docObj = document.getElementById("doc");
        var FileExt = docObj.value.substr(docObj.value.lastIndexOf(".")).toLowerCase();
        var fileSize = docObj.files[0].size;
        $("#srcImageDiv").html("<img id=srcImage />");

        if (fileSize / 1024 / 1024 > 2) {
            alert("你的文件太大了");
            return;
        }

        if (AllImgExt != 0 && AllImgExt.indexOf(FileExt + "|") == -1) {
            alert("你的文件格式不对");
            return;
        }
        ImgObj.src = window.URL.createObjectURL(docObj.files[0]);


        ImgObj.onload = function () {
            ImgWidth = ImgObj.width      //取得图片的宽度 
            ImgHeight = ImgObj.height;    //取得图片的高度

           

            var tempImage = document.getElementById("srcImage");
            tempImage.src = ImgObj.src;
            if (ImgWidth > maxWidth || ImgHeight > maxHeight) {
                scale = maxWidth / ImgWidth;
                if (ImgHeight * scale < maxHeight) {
                    tempImage.width = maxWidth;
                    tempImage.height = ImgHeight * scale;
                    tempImage.style.display = "none";
                    tempImage.style.visibility = "hidden";
                    // style="display: none; visibility: hidden;" width=350px height="250px"/>
                    tempImage.style.width = tempImage.width + "px";
                    tempImage.style.height = tempImage.height + "px";
                    tempImage.style.marginLeft = (maxWidth - tempImage.width) / 2 + "px";
                    tempImage.style.marginTop = (maxHeight - tempImage.height) / 2 + "px";
                }
                else {
                    scale = maxHeight / ImgHeight;
                    tempImage.width = ImgWidth * scale;
                    tempImage.height = maxHeight;

                    tempImage.style.display = "none";
                    tempImage.style.visibility = "hidden";
                    tempImage.style.width = tempImage.width + "px";
                    tempImage.style.height = tempImage.height + "px";
                    tempImage.style.marginLeft = (maxWidth - tempImage.width) / 2 + "px";
                    tempImage.style.marginTop = (maxHeight - tempImage.height) / 2 + "px";
                }

                if (tempImage.width < maxWidth && tempImage.height < maxHeight) {
                    tempImage.style.marginLeft = (tempImage.width - maxWidth) / 2 + "px";
                    tempImage.style.marginTop = (tempImage.height - maxHeight) / 2 + "px";

                }
            }
            else {

                tempImage.style.marginLeft = (maxWidth - ImgWidth) / 2 + "px";
                tempImage.style.marginTop = (maxHeight - ImgHeight) / 2 + "px";
            }

            var c = { "x": 13, "y": 7, "x2": 487, "y2": 107, "w": 474, "h": 100 };
            $('#srcImage').Jcrop({
                onChange: showPreview,
                onSelect: showPreview,
                setSelect: [c.x, c.y, c.x2, c.y2],
                aspectRatio: 1
            });

            function showPreview(coords) {
                if (parseInt(coords.w) > 0) {
                    //计算预览区域图片缩放的比例，通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
                    var rx = $("#preview_box").width() / coords.w;
                    var ry = $("#preview_box").height() / coords.h;

                    var tempImage = document.getElementById("srcImage");
                    $("#x").val(coords.x / tempImage.width);
                    $("#y").val(coords.y / tempImage.height);
                    $("#w").val(coords.w / tempImage.width);
                    $("#h").val(coords.h / tempImage.height);
                }
            };

            var dasdsa = $('.jcrop-holder');
            for (var i = 0; i < dasdsa.size() ; i++) {
                dasdsa[i].style.marginLeft = tempImage.style.marginLeft;
                dasdsa[i].style.marginTop = tempImage.style.marginTop;
            }
        }
    });


});



function hideSettingMessagelabel() {
    $("#settingNameMessage").css("visibility", "hidden");
    $("#settingEmailMessage").css("visibility", "hidden");
    $("#settingSchoolMessage").css("visibility", "hidden");
    $("#settingJobMessage").css("visibility", "hidden");
    $("#settingPhoneMessage").css("visibility", "hidden");
}
function isMobil(phoneNumber) {
    strReg = /^\d{11}$/;
    r = strReg.test(phoneNumber);
    return r;
}

function checkEmail(email) {
    strReg = /^\w+((-\w+)|(\.\w+))*\@{1}\w+\.{1}\w{2,4}(\.{0,1}\w{2}){0,1}/ig;
    r = email.search(strReg);
    if (r == -1) {
        return false;
    }
    return true;
}

function changeDetailSuccess(data) {
    var res = $.parseJSON(data);
    $("#setting-detailSaveMessage").css("visibility", "visible");
    if (res.Status == "success" && res.Message == "ok") {
        $("#setting-detailSaveMessage").html("更改成功");
        if (tempDetailSetting != null)
        {
            detailSetting = tempDetailSetting;
            tempDetailSetting = null;
        }
        return;
    }
    $("#setting-detailSaveMessage").html("更改失败");
}

function checkNamename(str) {
    var myReg = /^[^@\/\'\\\"#$%&\^\*]+$/;
    if (myReg.test(str))
        return true;
    return false;
}

function puloadState_Change(evt) {
    var request = evt.currentTarget;
    if (request.readyState == 4) {
        if (request.status == 200) {
            document.getElementById("changeHeadimageSaveButton").className = "booui_bluebutton booui_button_small";


            location.href = "/setting";
        }
    }
}

function uploadFailed(evt) {
    $("#uploadImageProgress").html("更改头像失败！");
    document.getElementById("changeHeadimageSaveButton").className = "booui_bluebutton booui_button_small";

}

function uploadProgress(evt) {
    var percentage = parseFloat(evt.loaded / evt.total);
    $("#uploadImageProgress").html("上传中...(" + parseInt(percentage*100 - 5) + "%)");
}

